import cv2
import numpy as np


from PIL import Image
import numpy as np
import cv2

# 使用PIL读取图像
pil_image = Image.open(r'C:\Users\zhonghai\Desktop\1.png')



# 转换为numpy数组
image = np.array(pil_image)




# 转换为灰度图像
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# 进行二值化处理，提取白色线条
_, binary_image = cv2.threshold(gray_image, 254, 255, cv2.THRESH_BINARY)

# # 进行边缘检测
edges = cv2.Canny(binary_image, 50, 150)

# 显示结果
cv2.imshow('Edges', binary_image)
cv2.waitKey(0)
cv2.destroyAllWindows()


# 显示结果
cv2.imshow('Edges', edges)
cv2.waitKey(0)
cv2.destroyAllWindows()



# 如果图像具有透明通道，将其转换为BGR格式
if image.shape[2] == 4:
    image = cv2.cvtColor(image, cv2.COLOR_RGBA2BGRA)
else:
    image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)

# 检查图像是否正确加载
# if image is None:
#     print("Failed to load image")
# else:
#     print("Image loaded successfully")

# # 读取图像
# image = cv2.imread('E:\docs\Pictures\照片美化\户型图\线框图.png', cv2.IMREAD_UNCHANGED)

# 检查图像是否具有透明通道
if image.shape[2] == 4:
    # 分离通道
    b, g, r, a = cv2.split(image)
    # 将透明背景变为白色
    image = cv2.merge((b, g, r))
    mask = a > 0
    image[mask == 0] = [255, 0, 0]

# 显示结果
cv2.imshow('Edges', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
# 如果需要保存结果
# cv2.imwrite('edges_output.png', image)

# 将图像转换为灰度图像
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# 应用高斯模糊以减少噪声
blurred = cv2.GaussianBlur(gray, (5, 5), 0)

# 使用Canny边缘检测
edges = cv2.Canny(blurred, 50, 150)

# 显示结果
cv2.imshow('Edges', edges)
cv2.waitKey(0)
cv2.destroyAllWindows()

# 如果需要保存结果
# cv2.imwrite('edges_output.png', edges)